package com.sun.filesigndemo.bussiness.druid;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * Mybatis配置
 */
@Configuration
@ConditionalOnClass({EnableTransactionManagement.class})
@Import({DruidDBConfig.class})
@MapperScan(basePackages = "com.sun.filesigndemo.bussiness.mapper")
public class MybatisConfiguration {

    @Value("${spring.datasource.readSize}")
    private String dataSourceSize;
    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;
    @Value("${mybatis.typeAliasesPackage}")
    private String typeAliasesPackage;
    @Resource(name = "dataSource")
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    @ConditionalOnMissingBean
    @ConfigurationProperties(prefix = "mybatis")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        // 配置mapper的扫描，找到所有的mapper.xml映射文件
        org.springframework.core.io.Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources(mapperLocations);
        sqlSessionFactoryBean.setMapperLocations(resources);
        sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sqlSessionFactoryBean.getObject();
    }
}
